/**
 * 获取字符串中的参数
 * @param {String} str 总字符串（'name1=xxx;name2=xxx'）
 * @param {String} name 要筛选的字段name1
 * @returns {string} 返回的字段xxx
 */
export function getPara (str, name) {
  // 查询检索的值
  let search = name + '='
  // 返回值
  let ret = ''
  if (str.length > 0) {
    let s = decodeURIComponent(str)
    let sd = s.indexOf(search)
    if (sd !== -1) {
      sd += search.length
      let end = s.indexOf(';', sd)
      if (end === -1) {
        end = s.length
      }
      ret = s.substring(sd, end)
    }
  }
  return ret
}
/**
 * 下载文件
 * @param {obj} res 文件api response
 * @returns {byte} 文件
 */
export function downFile (res, name, inlineName) {
  let reader = new FileReader()
  reader.readAsText(res.data, 'utf-8')
  reader.onload = function () {
    try {
      let jsonData = JSON.parse(this.result) // 说明是普通对象数据，后台转换失败
      if (jsonData.code) {
        Message({
          message: jsonData.message,
          type: 'error',
          duration: 3 * 1000
        })
      }
    } catch (err) { // 解析成对象失败，说明是正常的文件流
      downFileStream(res, name, inlineName)
    }
  }
}

function downFileStream (res, name, inlineName) {
  if (!res) {
    return
  }
  let filename = name || getPara(res.headers['content-disposition'], 'filename*')
  filename = filename.replace(`utf-8''`, '')
  if (inlineName && !name) {
    let a = filename.split('.')
    let newName = `${a[0]}${inlineName}.${a[1]}`
    filename = newName
  }
  if ('msSaveOrOpenBlob' in navigator) {
    // edge和ie的下载方法
    window.navigator.msSaveOrOpenBlob(new Blob([res.data]), filename)
  } else {
    let url = window.URL.createObjectURL(new Blob([res.data]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href)
    document.body.removeChild(link)
  }
}
